import React, {Component} from 'react'
import T from 'prop-types'

import './index.less'

class WeaRate extends Component {
    constructor(props) {
        super(props)
        const {defaultValue = 0, value = 0, total = 5, disabled = false} = props
        this.state = {
            currentValue: value || defaultValue,
            total: total,
            disabled: disabled
        }
    }

    componentWillReceiveProps(props) {
        const {value} = props
        this.setState({value: value,currentValue: value})
    }

    render() {
        const {className = "", ...rest} = this.props,
            {currentValue, total, disabled} = this.state,
            rates = []

        rates.push(<li
            className={"wea-r-item " + (currentValue ? "wea-r-text-hover" : "wea-r-text")}>{currentValue}分</li>)
        if (disabled) {
            for (let i = 0; i < total; i++) {
                if (i < currentValue) {
                    rates.push(
                        <li className="wea-r-item wea-r-score wea-r-score-selected icon-blog-Score"/>
                    )
                } else {
                    rates.push(
                        <li className="wea-r-item wea-r-score icon-blog-Score-o"/>
                    )
                }
            }
            return <ul className={"wea-rate " + className} {...rest}>{rates}</ul>
        } else {
            for (let i = 0; i < total; i++) {
                if (i < currentValue) {
                    rates.push(
                        <li
                            value={i + 1}
                            className="wea-r-item wea-r-score-hover wea-r-score-selected icon-blog-Score"
                            onMouseEnter={this.onMouseEnter}
                            onMouseLeave={this.onMouseLeave}
                        />
                    )
                } else {
                    rates.push(
                        <li
                            value={i + 1}
                            className="wea-r-item wea-r-score-hover icon-blog-Score-o"
                            onMouseEnter={this.onMouseEnter}
                            onMouseLeave={this.onMouseLeave}
                        />
                    )
                }
            }
            return (
                <ul className={"wea-rate " + className} onClick={this.onClick} {...rest}>
                    {rates}
                </ul>
            )
        }
    }

    onClick = (e) => {
        const {onChange} = this.props, value = e.target.value || 0;
        if (onChange)  {
            this.setState({
                value: value,
                currentValue: value
            });
            onChange(value)
        }
    }

    onMouseEnter = (e) => {
        this.setState({currentValue: e.target.value})
    }

    onMouseLeave = (e) => {
        this.setState({currentValue: this.state.value})
    }
}

WeaRate.propTypes = {}

WeaRate.defaultProps = {}

export default WeaRate